<?php
namespace App\Traits;

use App\Http\Controllers\HandleRedis;
use GatewayWorker\Lib\Gateway;

trait WorkerRequest
{
    protected static $request = [];//发送的数据

    protected static $client_id; //客户访问client_id

    protected static $f;//默认方法

    protected static function bindUid($uid = 0)
    {
        if(self::$client_id && $uid) {
            Gateway::bindUid(self::$client_id, $uid);//client_id绑定uid
        }
    }

    protected static function bindUserData($userData = [])
    {
        if(self::$client_id && $userData) {
            Gateway::setSession(self::$client_id, $userData);//根据client_id设置用户数据
        }
    }

    protected function sendToClient($data = [])
    {
        if (self::$client_id) {
            Gateway::sendToClient(self::$client_id,toJson($data));//发回给用户
        } else {
            echo toJson($data);
        }
    }

    /**
     * 发送给已登录的用户
     * @param array $data
     */
    public static function sendToHaveLoginUser($data = [])
    {
        if (self::$client_id) {
            $userClient = self::getAllLoginUser();
            foreach ($userClient as $v) {
                Gateway::sendToClient($v,toJson($data));//发回给用户
            }
        } else {
            echo toJson($data);
        }
    }


    /**
     * 获取所有登录的用户(根据指定的键)
     * @param string $field
     * @return array
     */
    public static function getAllLoginUser($field='client_id')
    {
        $data = [];
        $redis = HandleRedis::connectWorker();
        $allUserToken = $redis->keys('token_*');
        foreach ($allUserToken as $v) {
            $user = $redis->hGetAll($v);
            foreach ($user as $key=>$value) if($field == $key) $data[] = $value;
        }
        return $data;
    }
}
